package com.example.com.daervideo.fragments;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.com.daervideo.R;
import com.example.com.daervideo.activitys.MainActivity;
import com.example.com.daervideo.databinding.FragmentUserBinding;
import com.example.com.daervideo.entity.BaseListEntity;
import com.example.com.daervideo.entity.FansAndFollowNum;
import com.example.com.daervideo.entity.UserData;
import com.example.com.daervideo.fragments.video.ContentPagerAdapter;
import com.example.com.daervideo.initerface.ApiService;
import com.example.com.daervideo.popuwindow.ComplainPpwiondow;
import com.example.com.daervideo.utils.RetrofitClient;
import com.example.com.daervideo.vm.fragments.UserFragmentViewModel;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

import com.example.com.daervideo.BR;

import java.util.ArrayList;

/**
 * Created by i7-1 on 2018/12/3.
 */

public class UserFragment extends BaseFragment<FragmentUserBinding, UserFragmentViewModel> {

    private ArrayList<Fragment> tabFragments;
    private String[] tabIndicators = {"发布", "打赏", "分享"};
    private View tollbar;
    private MainActivity mainActivity;
    private int userType;
    private ComplainPpwiondow complainPpwiondow;
    private ApiService apiService;


    @Override
    public int initContentView() {
        return R.layout.fragment_user;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public UserFragmentViewModel initViewModel() {
        UserFragmentViewModel userFragmentViewModel = new UserFragmentViewModel(context);
        userFragmentViewModel.setUserType(userType);
        if (userType == 0) {
            binding.getRoot().findViewById(R.id.toolbar).setVisibility(View.GONE);
        }
        return userFragmentViewModel;
    }

    @Override
    public void initParam() {
        super.initParam();
        Bundle arguments = getArguments();
        userType = arguments.getInt("userType"); //0：自己，1:他人
    }

    @Override
    public void initData() {
        super.initData();

        mainActivity = (MainActivity) this.context;

        tabFragments = new ArrayList<>();
        for (String s : tabIndicators) {
            tabFragments.add(TabContentFragment.newInstance(s));
        }
        ContentPagerAdapter contentAdapter = new ContentPagerAdapter(this.getChildFragmentManager());
        contentAdapter.setLists(tabFragments, tabIndicators);

        binding.uViewpager.setAdapter(contentAdapter);
        apiService = RetrofitClient.getInstance().create(ApiService.class);
        tollbar = binding.getRoot().findViewById(R.id.toolbar);
        if (userType == 0) {
            initTab();
            getUserInfo();
            getNum();
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && userType == 1) {
            initToolbar();
            initTab();
            getUserInfo();
            getNum();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (userType == 0) {
            getUserInfo();
        }
    }

    private void initToolbar() {

        ImageView rimg = tollbar.findViewById(R.id.r_img);
        if (userType == 1) {
            complainPpwiondow = new ComplainPpwiondow(context);
        }

        rimg.setImageResource(R.mipmap.complain);
        tollbar.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RxBus.getDefault().post(1);
            }
        });
        rimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showComplainPpwiondow();
            }
        });

    }

    private void showComplainPpwiondow() {
        complainPpwiondow.showAtLocation(mainActivity.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    private void initTab() {
        binding.uTab.setTabMode(TabLayout.MODE_FIXED);
        binding.uTab.setTabTextColors(context.getResources().getColor(R.color.gray), context.getResources().getColor(R.color.white));
        binding.uTab.setSelectedTabIndicatorHeight(4);
        binding.uTab.setSelectedTabIndicatorColor(Color.WHITE);
        ViewCompat.setElevation(binding.uTab, 10);
        binding.uTab.setupWithViewPager(binding.uViewpager);
    }

    private void setUserInfo(UserData data) {
        getViewModel().setUserData(data);
    }

    private void setNum(FansAndFollowNum data) {
        getViewModel().setNum(data);
    }

    private void getUserInfo() {

        Observable<BaseResponse<UserData>> observable;
        if (userType == 1) {
            observable = apiService.getUserInfo("userinfo");
        } else {
            observable = apiService.getMineInfo();
        }
        observable.compose(RxUtils.bindToLifecycle(this)) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {

                    }
                })
                .subscribe(new Consumer<BaseResponse<UserData>>() {
                    @Override
                    public void accept(BaseResponse<UserData> response) throws Exception {
                        if (response.getCode() == 0) {
                            setUserInfo(response.getData());
                        } else {
                            ToastUtils.showShort(response.getMsg());
                        }
                    }
                }, new Consumer<ResponseThrowable>() {
                    @Override
                    public void accept(ResponseThrowable throwable) throws Exception {
                        ToastUtils.showShort(throwable.message);
                        throwable.printStackTrace();
                    }
                });


    }

    private void getNum() {
        Observable<BaseResponse<FansAndFollowNum>> observable2;
        if (userType == 1) {
            observable2 = apiService.getFansAndFollowNum("userinfo");
        } else {
            observable2 = apiService.getFansAndFollowNum();
        }
        observable2.compose(RxUtils.bindToLifecycle(this)) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                    }
                })
                .subscribe(new Consumer<BaseResponse<FansAndFollowNum>>() {
                    @Override
                    public void accept(BaseResponse<FansAndFollowNum> response) throws Exception {
                        if (response.getCode() == 0) {
                            setNum(response.getData());
                        } else {
                            ToastUtils.showShort(response.getMsg());
                        }
                    }
                }, new Consumer<ResponseThrowable>() {
                    @Override
                    public void accept(ResponseThrowable throwable) throws Exception {

                        ToastUtils.showShort(throwable.message);
                        throwable.printStackTrace();
                    }
                });
    }


}
